export class Util {

    constructor() {
    }

    //地址的单位
    private static displayTabbar(display?: string) {
        display = display || 'none';
        let elements = document.querySelectorAll(".tabbar");
        if (elements != null) {
            Object.keys(elements).map((key) => {
                elements[key].style.display = display;
            });
        }
    }

    static isNull(...objs) {
        let bol = false, fn = function (obj) {
            if (typeof obj == "undefined") {
                return true;
            } else if (obj == null) {
                return true;
            } else if (typeof obj == "string" && (obj.trim() === "" || obj === "undefined" || obj === "null")) {
                return true;
            } else if (typeof obj == "object" && Array.isArray(obj) && obj.length == 0) {
                return true;
            } else if (typeof obj == "object" && !Array.isArray(obj) && Object.keys(obj).length == 0) {
                return true;
            } else {
                return false;
            }
        }
        bol = objs.some(obj => {
            return fn(obj);
        });
        return bol;
    }

    static closest(el, selector) {
        let matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;

        while (el) {
            if (matchesSelector.call(el, selector)) {
                break;
            }
            el = el.parentElement;
        }
        return el;
    }

    static showTabbar() {
        this.displayTabbar('flex');
    }

    static hideTabbar() {
        this.displayTabbar('none');
    }

    //组装小区数据
    static getAddress(address: any[], city?: boolean): any[] {
        let dependentColumns = [];
        let chineseNameOfAddress: string[] = ['号楼', '单元', '层', '室'];
        let cityType = ['省', '市', '区'];
        if (city) {
            chineseNameOfAddress = [];
        }
        address.forEach((value, index) => {
            let addressDetail = {};
            addressDetail["name"] = value['ID'] || cityType[index];
            addressDetail["columnWidth"] = '100px';
            let optionsList = [];
            value['List'].forEach((element) => {
                let options = {};
                options["text"] = (element['text'] || element['TEXT']) + (chineseNameOfAddress[index - 1] || '');
                options["value"] = (element['value'] || element['VALUE']);
                // 街道小区
                if (index > 1) {
                    options["parentVal"] = element['parentVal']
                    options["SFYZ"] = element['SFYZ'];
                    options["DEGREE"] = element['DEGREE'];
                    options["TON"] = element['TON'];
                }
                //省市区
                if (index > 0 && city) {
                    options["parentVal"] = element['PARENTVAL'];
                }
                optionsList.push(options);
            });
            addressDetail["options"] = optionsList;
            dependentColumns[city ? index : index - 1] = addressDetail;
        });
        return dependentColumns;
    }

    /**
     * 时间格式化
     * @param date
     * @param sFormat
     */
    static dateFormat(date: Date, sFormat: string = 'yyyy-MM-dd'): string {
        let time = {
            Year: 0,
            TYear: '0',
            Month: 0,
            TMonth: '0',
            Day: 0,
            TDay: '0',
            Hour: 0,
            THour: '0',
            hour: 0,
            Thour: '0',
            Minute: 0,
            TMinute: '0',
            Second: 0,
            TSecond: '0',
            Millisecond: 0
        };
        time.Year = date.getFullYear();
        time.TYear = String(time.Year).substr(2);
        time.Month = date.getMonth() + 1;
        time.TMonth = time.Month < 10 ? "0" + time.Month : String(time.Month);
        time.Day = date.getDate();
        time.TDay = time.Day < 10 ? "0" + time.Day : String(time.Day);
        time.Hour = date.getHours();
        time.THour = time.Hour < 10 ? "0" + time.Hour : String(time.Hour);
        time.hour = time.Hour < 13 ? time.Hour : time.Hour - 12;
        time.Thour = time.hour < 10 ? "0" + time.hour : String(time.hour);
        time.Minute = date.getMinutes();
        time.TMinute = time.Minute < 10 ? "0" + time.Minute : String(time.Minute);
        time.Second = date.getSeconds();
        time.TSecond = time.Second < 10 ? "0" + time.Second : String(time.Second);
        time.Millisecond = date.getMilliseconds();

        return sFormat.replace(/yyyy/ig, String(time.Year))
            .replace(/yyy/ig, String(time.Year))
            .replace(/yy/ig, time.TYear)
            .replace(/y/ig, time.TYear)
            .replace(/MM/g, time.TMonth)
            .replace(/M/g, String(time.Month))
            .replace(/dd/ig, time.TDay)
            .replace(/d/ig, String(time.Day))
            .replace(/HH/g, time.THour)
            .replace(/H/g, String(time.Hour))
            .replace(/hh/g, time.Thour)
            .replace(/h/g, String(time.hour))
            .replace(/mm/g, time.TMinute)
            .replace(/m/g, String(time.Minute))
            .replace(/ss/ig, time.TSecond)
            .replace(/s/ig, String(time.Second))
            .replace(/fff/ig, String(time.Millisecond))
    }

    /**
     * 根据毫秒数获取 天、时、分、秒
     * @param ms 两个时间差的毫秒数
     * @param tg
     */
    static getDayOrHourMinuteOrSecond(ms, tg) {
        //相差的毫秒数
        let minutes = 1000 * 60;
        let hours = minutes * 60;
        let days = hours * 24;
        //求出天数
        let d = Math.floor(ms / days);
        //求出除开天数，剩余的毫秒数
        ms %= days;
        let h = Math.floor(ms / hours);
        ms %= hours;
        let m = Math.floor(ms / minutes);
        ms %= minutes;
        let s = Math.floor(ms / 1000);
        //返回所需值并退出函数
        switch (tg) {
            case 'd':
                return d;
            case 'h':
                return h;
            case 'm':
                return m;
            case 's':
                return s;
        }
    }

    /**
     * 更换Navbar组件的回退事件
     * @param navbar Navbar对象
     * @param navctrl 当前视图的导航控制器
     */
    static replaceBackButtonEvent(navbar, navctrl, events) {
        navbar.backButtonClick = () => {
            events.publish("isBackButtonOfIonic");
            navctrl.pop();
        };
    }

    /**
     * 日期 Date 转 String
     * */
    public static dateToString(date: Date, format: string = 'YYYY-MM-DD') {
        let FullYear = date.getFullYear();
        let Month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
        let Day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        let Hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
        let Minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
        let Seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();

        return format.replace("yyyy", String(FullYear))
            .replace("mm", String(Month))
            .replace("dd", String(Day))
            .replace("hh", String(Hours))
            .replace("mi", String(Minutes))
            .replace("ss", String(Seconds))
            .replace("YYYY", String(FullYear))
            .replace("MM", String(Month))
            .replace("DD", String(Day))
            .replace("HH", String(Hours))
            .replace("MI", String(Minutes))
            .replace("SS", String(Seconds));
    }

    /**
     * 日期 String 转 Date
     * */
    public static stringToDate(date: string): Date {
        return new Date(Date.parse(date));//格式 2017-10-16 14:23:15
    }

    /**
     * 获取年月日
     * */
    public static getMonth(add, format: string = 'YYYY-MM') {
        let d = new Date();
        if (add instanceof Date) {
            d = add;
        } else if (!Util.isNull(add)) {
            d.setMonth(d.getMonth() + add * 1);
        }
        return Util.dateToString(d, format);
    }

    /**
     * 获取年月日
     * */
    public static getYear(add, format: string = 'YYYY') {
        let d = new Date();
        if (add instanceof Date) {
            d = add;
        } else if (!Util.isNull(add)) {
            d.setFullYear(d.getFullYear() + add * 1);
        }
        return Util.dateToString(d, format);
    }

    /**
     * 获取年月日
     * */
    public static getWeek(add, format: string = 'YYYY.MM.DD', split: string = "-") {
        return Util.getWeekStart(add, format) + split + Util.getWeekEnd(add, format);
    }

    /**
     * 获取年月日
     * */
    public static getWeekStart(add, format: string = 'YYYY-MM-DD') {
        let d = new Date();
        if (add instanceof Date) {
            d = add;
        } else if (!Util.isNull(add)) {
            d.setDate(d.getDate() + add * 1);//当前日期+几天
        }

        d.setDate(d.getDate() - d.getDay());
        return Util.dateToString(d, format);
    }

    /**
     * 获取年月日
     * */
    public static getWeekEnd(add, format: string = 'YYYY-MM-DD') {
        let d = new Date();
        if (add instanceof Date) {
            d = add;
        } else if (!Util.isNull(add)) {
            d.setDate(d.getDate() + add * 1);//当前日期+几天
        }

        d.setDate(d.getDate() + (6 - d.getDay()));
        return Util.dateToString(d, format);
    }

    /**
     * 获取年月日
     * */
    public static getDate(addDay, format: string = 'YYYY-MM-DD') {
        let d = new Date();
        if (addDay instanceof Date) {
            d = addDay;
        } else if (!Util.isNull(addDay)) {
            d.setDate(d.getDate() + addDay * 1);//当前日期+几天
        }
        return Util.dateToString(d, format);
    }

  /**
   * 格式化日期为：年-月-日
   * @param date
   */
  public static getymd(date: Date): string {
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    let d = date.getDate();
    return y + '-' + m + '-' + d
  }

    /**
     * 获取时分秒
     * */
    public static getTime() {
        let d = new Date();
        let Hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
        let Minutes = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
        let Seconds = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds();
        let str = Hours + ':' + Minutes + ':' + Seconds;
        return str;
    }

    /**
     * 获取年月日时分秒
     * */
    public static getDateTime(addDay, format: string = 'YYYY-MM-DD HH:MI:SS') {
        let d = new Date();
        if (addDay instanceof Date) {
            d = addDay;
        } else if (!Util.isNull(addDay)) {
            d.setDate(d.getDate() + addDay * 1);//当前日期+几天
        }
        return Util.dateToString(d, format);
    }

    /**
     * 解决数字精度问题
     * */
    public static precision(number) {
        number = number.toString();
        let cf = 0;
        let xs = false;
        for (let i = 0; i < number.length; i++) {
            let str = number[i];
            if (str == ".") {
                xs = true;
            } else if (xs) {
                if (cf == 8) {
                    let ws = number.substring(number.indexOf("."), i - 8).length - 2;
                    return Number(Number(number).toFixed(ws));
                } else if (number[i] == number[i - 1]) {
                    cf++;
                } else {
                    cf = 0
                }
            }
        }
        return Number(number);
    }

    /**
     * 时间比较
     * */
    public static formatDate(date) {
        let today = new Date(new Date(new Date(new Date().setHours(0)).setMinutes(0)).setSeconds(0)).getTime();
        let yesterday = today - 24 * 60 * 60 * 1000;
        if (date >= today) return '今天';
        else if (date >= yesterday) return '昨天';
        else return '更早';
    }

  /**
   * 日期比较
   * @param date1
   * @param date2
   */
  public static dateDiff(date1: Date, date2: Date): boolean {
    let result = false;
    if (date1.getFullYear() > date2.getFullYear()) {
      result = true;
    } else if (date1.getFullYear() == date2.getFullYear()) {
      if (date1.getMonth() > date2.getMonth()) {
        result = true;
      } else if (date1.getMonth() == date2.getMonth()) {
        if (date1.getDate() > date2.getDate()) {
          result = true;
        }
      }
    }
    return result;
  }

}
